package com.itheima.config;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        // 查询用户的角色
        List<Role> roles = userMapper.loadRolesByUserId(user.getId());
        // 把角色转换成数组
        String[] roleCodes = roles.stream()
                .map(Role::getKeyword)
                .collect(Collectors.toList())
                .toArray(new String[0]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(roleCodes);
        // 设置用户的权限
//        org.springframework.security.core.userdetails.User user1 = new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorityList);
        user.setAuthorities(authorityList);
        return user;
    }


//    2. 重写 public UserDetails loadUserByUsername(String username)方法
//    3. 调用用户服务获取用户信息
//    4. 查询当前用户对应的角色和权限
//    5. 封装当前用户的角色和权限
//    6. 返回带用户名，密码，权限列表的user对象User(username,user.getPassword(),list)
//public static void main(String[] args) {
//    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//    System.out.println(bCryptPasswordEncoder.encode("123456"));
//}
}
